<?php

namespace App\Http\Requests;

use App\Models\Patient;
use Illuminate\Database\Query\Builder;
use Illuminate\Validation\Rule;

class AuxiliaryUpdateRequest extends AuxiliaryStoreRequest
{
    /**
     * Get the validation rules that apply to the request.
     * @return array
     */
    public function rules()
    {
        $rules = parent::rules();

        $rules['id'] = [
            'required_without:record_id', 'integer', 'min:1',
            Rule::exists('st_medical_auxiliarycheck', 'id')->where(function (Builder $query) {
                $query->where('record_id', $this->input('record_id'));
            }),
        ];

        array_pop($rules['record_id']);
        $rules['record_id'][0] = 'required_without:id';
        $rules['record_id'][] = Rule::exists('st_medical_records', 'id')->where(function (Builder $query) {
            $query->whereNull('deleted_at');
            $user = \Auth::user();
            if ($user instanceof Patient) {
                $query->where(['patient_id' => $user->id])->join(
                    'st_medical_diagnose', 'st_medical_diagnose.record_id', 'st_medical_records.id'
                );
            } else if (!$user->isDoctorsAdmin() && !$user->isAdmin()) {
                $query->where(['doctor_id' => $user->id]);
            }
        });

        return $rules;
    }

    public function messages()
    {
        $messages = parent::messages();

        $messages['id.required'] = '缺少 辅助检查ID。';
        $messages['id.integer']  = '辅助检查ID 必须是一个整数。';
        $messages['id.min']      = '辅助检查ID 必须大于 :min。';
        $messages['id.exists']   = '辅助检查ID 不存在，或与病历ID不匹配。';

        return $messages;
    }
}
